package com.qidianit.mes.pro.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qidianit.mes.pojo.Result;
import com.qidianit.mes.pojo.pro.Workflow;
import com.qidianit.mes.pro.mapper.ProcessMapper;
import com.qidianit.mes.pro.mapper.WorkflowMapper;
import com.qidianit.mes.pro.service.WorkflowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 工艺流程服务实现类
 * 实现工艺流程的各项业务逻辑
 */
@Service
public class WorkflowServiceImpl implements WorkflowService {

    @Autowired
    private WorkflowMapper workflowMapper;
    @Autowired
    private ProcessMapper processMapper;

    @Override
    public Result<List<Workflow>> selectListByMaterialCode(String code) {
        List<Workflow> workflows = workflowMapper.selectListByMaterialCode(code);
        workflows.forEach(workflow -> {
            workflow.setProcesses(processMapper.selectProcessByWorkflowId(workflow.getId()));
        });
        return Result.success(workflows);
    }

    @Override
    public Result<PageInfo<Workflow>> selectList(Workflow workflow, int pageNum, int pageSize) {
        try {
            // 开启分页
            PageHelper.startPage(pageNum, pageSize);
            // 执行查询
            List<Workflow> workflowList = workflowMapper.selectList(workflow);
            // 封装分页结果
            PageInfo<Workflow> pageInfo = new PageInfo<>(workflowList);
            return Result.success(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询工艺流程列表失败：" + e.getMessage());
        }
    }

    @Override
    public Result<Workflow> selectByCode(String workflowCode) {
        try {
            if (workflowCode == null || workflowCode.trim().isEmpty()) {
                return Result.error("工艺流程编号不能为空");
            }
            
            Workflow workflow = workflowMapper.selectByCode(workflowCode);
            if (workflow != null) {
                return Result.success(workflow);
            } else {
                return Result.error("未找到编号为【" + workflowCode + "】的工艺流程");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询工艺流程失败：" + e.getMessage());
        }
    }

    @Transactional
    @Override
    public Result saveWorkflow(Workflow workflow) {
        try {
            // 校验必填参数
            if (workflow.getWorkflowCode() == null || workflow.getWorkflowCode().trim().isEmpty()) {
                return Result.error("工艺流程编号不能为空");
            }
            if (workflow.getWorkflowName() == null || workflow.getWorkflowName().trim().isEmpty()) {
                return Result.error("工艺流程名称不能为空");
            }

            // 校验编号唯一性
            Workflow existWorkflow = workflowMapper.selectByCode(workflow.getWorkflowCode());
            if (existWorkflow != null) {
                return Result.error("工艺流程编号【" + workflow.getWorkflowCode() + "】已存在，请更换");
            }

            // 执行保存操作
            int rows = workflowMapper.saveWorkflow(workflow);
            if (rows > 0) {
                return Result.success(workflow);
            } else {
                return Result.error("新增工艺流程失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("新增工艺流程失败：" + e.getMessage());
        }
    }

    @Transactional
    @Override
    public Result updateById(Workflow workflow) {
        try {
            // 校验必要参数
            if (workflow.getId() == null) {
                return Result.error("ID不能为空");
            }
            if (workflow.getWorkflowCode() == null || workflow.getWorkflowCode().trim().isEmpty()) {
                return Result.error("工艺流程编号不能为空");
            }
            if (workflow.getWorkflowName() == null || workflow.getWorkflowName().trim().isEmpty()) {
                return Result.error("工艺流程名称不能为空");
            }


            // 校验编号唯一性（如果编号有修改）
            Workflow oldWorkflow = workflowMapper.selectById(workflow.getId());
            if (oldWorkflow == null) {
                return Result.error("未找到ID为【" + workflow.getId() + "】的工艺流程");
            }

            // 如果编号发生变化，检查新编号是否已存在
            if (!oldWorkflow.getWorkflowCode().equals(workflow.getWorkflowCode())) {
                Workflow existWorkflow = workflowMapper.selectByCode(workflow.getWorkflowCode());
                if (existWorkflow != null) {
                    return Result.error("工艺流程编号【" + workflow.getWorkflowCode() + "】已存在，请更换");
                }
            }

            // 执行更新操作
            int rows = workflowMapper.updateById(workflow);
            if (rows > 0) {
                return Result.success("更新工艺流程成功");
            } else {
                return Result.error("更新工艺流程失败，未找到对应的记录或数据未发生变化");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新工艺流程失败：" + e.getMessage());
        }
    }

    @Transactional
    @Override
    public Result deleteById(Long id) {
        try {
            if (id == null) {
                return Result.error("ID不能为空");
            }

            // 检查记录是否存在
            Workflow workflow = workflowMapper.selectById(id);
            if (workflow == null) {
                return Result.error("未找到ID为【" + id + "】的工艺流程");
            }

            // 执行删除操作
            int rows = workflowMapper.deleteById(id);
            if (rows > 0) {
                return Result.success("删除工艺流程成功");
            } else {
                return Result.error("删除工艺流程失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除工艺流程失败：" + e.getMessage());
        }
    }

    @Transactional
    @Override
    public Result batchDelete(Long[] ids) {
        try {
            if (ids == null || ids.length == 0) {
                return Result.error("请选择要删除的工艺流程");
            }

            int deleteCount = workflowMapper.deleteByIds(ids);
            if (deleteCount > 0) {
                return Result.success("批量删除成功，共删除" + deleteCount + "条工艺流程");
            } else {
                return Result.error("批量删除失败，未找到对应的记录");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("批量删除工艺流程失败：" + e.getMessage());
        }
    }
}
